<?php

/**
 * Countries Helper
 *
 * An country hook helper for demonstrating hook system.
 *
 * @category Helper
 * @package  Croogo
 * @version  1.0
 * @author   Fahad Ibnay Heylaal <contact@fahad19.com>
 * @license  http://www.opensource.org/licenses/mit-license.php The MIT License
 * @link     http://www.croogo.org
 */
class CountriesHelper extends AppHelper {

        /**
         * Other helpers used by this helper
         *
         * @var array
         * @access public
         */
        public $helpers = array(
            'Html',
            'Form',
            'Session',
            'Js',
            'Layout',
        );
        public $city = null;

        public function __construct(View $view, $settings = array()) {
                parent::__construct($view);
                $this->_setupEvents();
        }

        /**
         * setup events
         */
        protected function _setupEvents() {
                $events = array(
                    'Helper.Layout.beforeFilter' => array(
                        'callable' => 'filter', 'passParams' => true,
                    ),
                );
                $eventManager = $this->_View->getEventManager();
                foreach ($events as $name => $config) {
                        $eventManager->attach(array($this, 'filter'), $name, $config);
                }
        }

        /**
         * Show nodes list
         *
         * @param string $alias Node query alias
         * @param array $options (optional)
         * @return string
         */
        public function cityList($alias, $options = array()) {
                $_options = array(
                    'link' => true,
                    //'plugin' => 'countries',
                    'controller' => 'cities',
                    'action' => 'view',
                    'element' => 'city_list',
                );
                $options = array_merge($_options, $options);
                $output = '';
                if (isset($this->_View->viewVars['cities_for_layout'][$alias])) {
                        $output = $this->_View->element($options['element'], array(
                            'alias' => $alias,
                            'citisList' => $this->_View->viewVars['cities_for_layout'][$alias],
                            'options' => $options,
                                ));
                }
                return $output;
        }

        /**
         * Filter content for Nodes
         *
         * Replaces [city:unique_name_for_query] or [ci:unique_name_for_query] with City list
         *
         * @param string $content
         * @return string
         */
        public function filter($content) {
                preg_match_all('/\[(city|ci):([A-Za-z0-9_\-]*)(.*?)\]/i', $content, $tagMatches);
                for ($i = 0, $ii = count($tagMatches[1]); $i < $ii; $i++) {
                        $regex = '/(\S+)=[\'"]?((?:.(?![\'"]?\s+(?:\S+)=|[>\'"]))+.)[\'"]?/i';
                        preg_match_all($regex, $tagMatches[3][$i], $attributes);
                        $alias = $tagMatches[2][$i];
                        $options = array();
                        for ($j = 0, $jj = count($attributes[0]); $j < $jj; $j++) {
                                $options[$attributes[1][$j]] = $attributes[2][$j];
                        }
                        $content = str_replace($tagMatches[0][$i], $this->cityList($alias, $options), $content);
                }
                return $content;
        }

        /**
         * Show countries is Active
         *
         * @param array $options (optional)
         * @return string
         */
        public function countries($options = array()) {
                $_options = array(
                    'tag' => '',
                    'tagAttributes' => array(),
                    'selected' => 'selected',
                    'type' => 'TEXT AND IMAGE', // IMAGE OR TEXT OR TEXT AND IMAGE
                    'element' => 'Countries.countries',
                    'class' => '',
                    'onclick' => '',
                    'classParent' => 'countries',
                    'show_title'=>true
                );
                $options = array_merge($_options, $options);

                if (!isset($this->_View->viewVars['countries_for_layout'])) {
                        return false;
                }
                $countries = $this->_View->viewVars['countries_for_layout'];
                $output = $this->_View->element($options['element'], array(
                    'countries' => Hash::sort($countries, '{n}.Country.weight', 'DESC'),
                    'options' => $options,
                        ));
                return $output;
        }

        /**
         * Nested Links
         *
         * @param array $langs model output
         * @param array $options (optional)
         * @return string
         */
        public function countryItem($countries, $options = array()) {
                $_options = array();
                $options = array_merge($_options, $options);

                $output = '';
                foreach ($countries as $country) {
                        $linkAttr = array(
                            'id' => 'country-' . $country['Country']['id'],
                            'title' => $country['Country']['name'],
                            'class' => $options['class'],
                            'onclick' => str_replace(':id', $country['Country']['id'], $options['onclick'])
                        );
                        foreach ($linkAttr as $key => $attr) {
                                if (empty($attr)) {
                                        unset($linkAttr[$key]);
                                }
                        }

                        /*
                          // set selected
                          if (empty($this->params['locale']) && Configure::read('Site.locale')==$lang['Language']['alias']) {
                          $linkAttr['class'] .= ' ' . $options['selected'];
                          } else if(!empty($this->params['locale']) && $this->params['locale']==$lang['Language']['alias']) {
                          $linkAttr['class'] .= ' ' . $options['selected'];
                          }
                         */

                        //set image icon or text for country
                        switch ($options['type']) {
                                case 'TEXT':
                                        $linkOutput = $this->Html->link($country['Country']['name'], 'javascript:void(0)', $linkAttr);
                                        break;
                                case 'TEXT AND IMAGE':
                                        $linkAttr['escape'] = false;
                                        $linkOutput = $this->Html->link($this->Html->image(strtolower($country['Country']['alias']) . '_icon.png') . ' ' . $this->Html->tag('strong', $country['Country']['name']), 'javascript:void(0)', $linkAttr);
                                        break;
                                default:
                                        $linkAttr['escape'] = false;
                                        $linkOutput = $this->Html->link($this->Html->image(strtolower($country['Country']['alias']) . '_icon.png'), 'javascript:void(0)', $linkAttr);
                                        break;
                        }

                        if (!empty($options['tag'])) {
                                $linkOutput = $this->Html->tag($options['tag'], $linkOutput);
                        }

                        $output .= $linkOutput;
                }

                return $output;
        }

        /**
         * getListCountry
         *
         * @return void
         */
        public function getListCountry($limit = false) {
                if($limit){
                        return ClassRegistry::init('Countries.Country')->find('list', array('conditions' => array('Country.id' => json_decode(Configure::read('Countries.country')))));
                }else{
                        return ClassRegistry::init('Countries.Country')->find('list');
                }
        }

        /**
         * getListCountry
         *
         * @return void
         */
        public function getListCity() {
				if(!empty($country_id)){
					return ClassRegistry::init('City')->find('list');
				}
                return ClassRegistry::init('City')->find('list');
        }

        /**
         * getListCountry
         *
         * @return void
         */
        public function getListProvince($city_id = null) {
				if(!empty($city_id)){
					return ClassRegistry::init('Province')->find('list',array('conditions'=>array('Province.city_id'=>$city_id)));
				}
                return ClassRegistry::init('Province')->find('list');
        }

        /**
         * countCity
         *
         * @return void
         */
        public function countCity($country_id = 229) {
                return ClassRegistry::init('Countries.City')->find('count',array('conditions'=>array('City.country_id'=>$country_id)));
        }
/**
 * 
 * @param type $return
 * @param type $link
 * @param type $tag
 * @return type
 */        
        public function areas($return = false, $link = false, $tag = false) {
                $areas = ClassRegistry::init('Countries.Area')->find('all',array(
                        'cache' => array(
                          'config' => 'croogo_areas'
                        ),
                ));

                if($return==true){
                        return $areas;
                }else{
                        $list = array();
                        $i = 1;
                        if(isset($tag['attr']['class'])){
                                $class = $tag['attr']['class'];
                        }else{
                                $class = '';
                        }                  
                        foreach($areas as $area){        
                                if($tag==false){
                                        if($link==false){
                                                $list[] = $area['Area']['name'];
                                        }else{
                                                $link = Hash::merge(array('link'=>'#','attr'=>array('title'=>$area['Area']['name'])), $link);
                                                $list[] = $this->Html->link($area['Area']['name'],$link['link'],$link['attr']);
                                        }
                                }else{
                                        $tag['attr']['class'] = $class;
                                        $tag = Hash::merge(array('tag'=>'li','attr'=>array('escape'=>false)), $tag);
                                        if(isset($tag['attr']['class'])){
                                                $tag['attr']['class'] = str_replace(':id',$area['Area']['id'],$tag['attr']['class']);
                                        }
                                        
                                        if($i==1){
                                                $tag['attr']['class'] = $tag['attr']['class'].' active';
                                        }else if(count($areas)==$i){
                                                $tag['attr']['class'] = $tag['attr']['class'].' nobg';
                                        }
                                        
                                        if($link==false){
                                                $list[] = $this->Html->tag($tag['tag'],$area['Area']['name'],$tag['attr']);
                                        }else{
                                                $link = Hash::merge(array('link'=>'#','attr'=>array('title'=>$area['Area']['name'])), $link);
                                                $list[] = $this->Html->tag($tag['tag'],$this->Html->link($area['Area']['name'],$link['link'],$link['attr']),$tag['attr']);
                                        }
                                }
                                $i++;
                        }
                        return implode('',$list);
                }                
                
        }

        public function cityTab($return = false) {
                $areas = ClassRegistry::init('Countries.Area')->find('all',array(
                        'cache' => array(
                          'config' => 'croogo_areas'
                        ),
                ));

                if($return==true){
                        return $areas;
                }else{
                        $list = array();
                        $data_tabs = array();
                        foreach($areas as $area){
                                $rows = array_chunk($area['City'],4);
                                $data_rows = array();                                
                                foreach($rows as $row){
                                        $item = array();
                                        foreach($row as $row1){
                                                $item[] = $this->Html->tag('li',$this->Html->link($row1['name'],array(
                                                    'plugin'=>'countries',
                                                    'controller'=>'cities',
                                                    'action'=>'view',
                                                    'slug'=>  strtolower($row1['alias'])
                                                ),array(
                                                    'title'=>$row1['name']
                                                )),array(
                                                   'escape'=>false 
                                                ));                                                
                                        }
                                        $data_rows[] = $this->Html->tag('div',$this->Html->tag('ul',implode('',$item),array('escape'=>false)),array('escape'=>false,'class'=>'itemt_tab'));
                                }                                
                                $data_tabs[] = $this->Html->tag('div',
                                        implode('', $data_rows).
                                        $this->Html->tag('div','',array('class'=>'clear')).
                                        $this->Html->tag('div',$this->Html->link('More &gt;&gt;','#',array('title'=>'More &gt;&gt;','escape'=>false)),array('class'=>'more','escape'=>false)),
                                        array('class'=>'tab_main tb_main'.$area['Area']['id'])
                                );
                        }
                        return implode('',$data_tabs);
                }                
                
        }        
        
}
